package com.whpost.service.tools;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import lombok.Data;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ExcelProcessing {

    public static void main(String[] args) {
        String sourceFilePath = "d:\\报名数据.xls";
        String targetFilePath = "d:\\报名数据_处理后.xlsx";

        List<ExcelData> dataList = new ArrayList<>();

        // 读取 Excel 文件
        EasyExcel.read(new File(sourceFilePath), ExcelData.class, new AnalysisEventListener<ExcelData>() {
            @Override
            public void invoke(ExcelData data, AnalysisContext context) {
                // 处理手机号、身份证号和紧急联系人手机号
                data.setSJHM(decryptIfNeeded(data.getSJHM()));
                data.setSFZHM(decryptIfNeeded(data.getSFZHM()));
                data.setJJLXR_SJHM(decryptIfNeeded(data.getJJLXR_SJHM()));

                dataList.add(data);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 写入新的 Excel 文件
                ExcelWriterBuilder writerBuilder = EasyExcel.write(new File(targetFilePath), ExcelData.class);
                ExcelWriterSheetBuilder sheetBuilder = writerBuilder.sheet("Sheet1");
                sheetBuilder.doWrite(dataList);
            }
        }).sheet().doRead();
    }

    // 模拟 Url.decrypt() 方法，实际使用时请替换为真实的解密逻辑
    private static String decryptIfNeeded(String input) {
        if (isPhoneNumber(input) || isIdCardNumber(input)) {
            return input;
        }
        try {
            // 这里替换为实际的解密逻辑
            return Url.decrypt(input);
        } catch (Exception e) {
            return "";
        }
    }

    // 简单判断是否为手机号，实际判断逻辑可能更复杂
    private static boolean isPhoneNumber(String input) {
        return input != null && input.matches("^1[3-9]\\d{9}$");
    }

    // 简单判断是否为身份证号，实际判断逻辑可能更复杂
    private static boolean isIdCardNumber(String input) {
        return input != null && (input.matches("^\\d{15}$") || input.matches("^\\d{18}$") || input.matches("^\\d{17}[Xx]$"));
    }
}